<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">






  
  
  <link rel="stylesheet" media="all" href="/lib/Han/dist/han.min.css?v=3.3">




<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.png?v=5.1.4">


  <link rel="mask-icon" href="/images/favicon.png?v=5.1.4" color="#222">





  <meta name="keywords" content="APP开发," />





  <link rel="alternate" href="/atom.xml" title="平步青云win" type="application/atom+xml" />






<meta name="description" content="Java基本知识，包括：数组、数组列表，for、while循环和自定义类">
<meta name="keywords" content="APP开发">
<meta property="og:type" content="article">
<meta property="og:title" content="Java数组、列表、循环和自定义类">
<meta property="og:url" content="https://zxpgo.github.io/2018/11/09/Java数组、列表、循环和自定义类/index.html">
<meta property="og:site_name" content="平步青云win">
<meta property="og:description" content="Java基本知识，包括：数组、数组列表，for、while循环和自定义类">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://i.imgur.com/YaVcg0c.png">
<meta property="og:image" content="https://i.imgur.com/9kC91Ix.png">
<meta property="og:image" content="https://i.imgur.com/QCdOcJR.png">
<meta property="og:image" content="https://i.imgur.com/QV3VRHa.png">
<meta property="og:image" content="https://i.imgur.com/kZ7FtQP.png">
<meta property="og:image" content="https://i.imgur.com/YldFuZr.png">
<meta property="og:image" content="https://i.imgur.com/oESlPBy.png">
<meta property="og:image" content="https://i.imgur.com/XSCkvuw.png">
<meta property="og:updated_time" content="2018-11-14T12:47:17.095Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java数组、列表、循环和自定义类">
<meta name="twitter:description" content="Java基本知识，包括：数组、数组列表，for、while循环和自定义类">
<meta name="twitter:image" content="https://i.imgur.com/YaVcg0c.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"right","display":"post","offset":10,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: 'PAO8LM7QB1',
      apiKey: '',
      indexName: 'Blog',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zxpgo.github.io/2018/11/09/Java数组、列表、循环和自定义类/"/>





  <title>Java数组、列表、循环和自定义类 | 平步青云win</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?7a4517a3ce6d7c50203655d056f01ac3";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">平步青云win</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description"></h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-随笔">
          <a href="/sui" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            随笔
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
			
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zxpgo.github.io/2018/11/09/Java数组、列表、循环和自定义类/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zxp">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="平步青云win">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Java数组、列表、循环和自定义类</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-11-09T08:33:14+08:00">
                2018-11-09
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/APP开发/" itemprop="url" rel="index">
                    <span itemprop="name">APP开发</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2018/11/09/Java数组、列表、循环和自定义类/" class="leancloud_visitors" data-flag-title="Java数组、列表、循环和自定义类">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <p>Java基本知识，包括：数组、数组列表，for、while循环和自定义类<a id="more"></a></p>
<p>8种基本类型：</p>
<p><img src="https://i.imgur.com/YaVcg0c.png" alt=""></p>
<p>注意：String不是基本类型，它是一个字符串对象。其中第一个字母<code>S</code>需要大写。</p>
<h3 id="数组Array"><a href="#数组Array" class="headerlink" title="数组Array"></a>数组Array</h3><p>创建一个数组：</p>
<pre><code>int [] shoeSizes = new int[3];
</code></pre><p>初始化数组元素：</p>
<pre><code>shoeSize[0] = 5;
shoeSize[1] = 7;
shoeSize[2] = 10;
</code></pre><p>获取数组的长度：</p>
<pre><code>shoeSize.length
</code></pre><p>创建一个数组，并初始化，通过输入到日志消息查看是否实现：</p>
<pre><code>String [] words = new String[10];
words[0] = &quot;one&quot;;
words[1] = &quot;two&quot;;
words[2] = &quot;three&quot;;
words[3] = &quot;four&quot;;
words[4] = &quot;five&quot;;
words[5] = &quot;six&quot;;
words[6] = &quot;seven&quot;;
words[7] = &quot;eight&quot;;
words[8] = &quot;nine&quot;;
words[9] = &quot;ten&quot;;
Log.v(&quot;NumbersActivity&quot;,&quot;Word at index 0: &quot; + words[0]);
</code></pre><h3 id="数组列表ArrayList"><a href="#数组列表ArrayList" class="headerlink" title="数组列表ArrayList"></a>数组列表ArrayList</h3><p><img src="https://i.imgur.com/9kC91Ix.png" alt=""></p>
<ul>
<li>数组的大小是固定的，而数组列表的大小可以改变；</li>
<li>数组中可以存储原始数据类型（比如int,double）和对象类型，但数组列表只能存储对象类型；</li>
<li>数组不是类，不需要方法来访问和修改元素；数组列表被定义成类，意味着数组列表的每个实例都是对象，具有方法供我们访问和修改数据。</li>
</ul>
<p>ArrayList类继承于AbstractList类，AbstractList是一个抽象类，抽象类是部分实现的类，表示某些方法已经实现，某些方法还是空着的。</p>
<p>Java中有很多其他类型的列表，比如链表、堆栈和向量等。</p>
<ul>
<li>具体类：具有状态和所有方法的实现，比如ArrayList</li>
<li>抽象类：部分方法实现，比如AbstractList</li>
<li>接口：所有方法都没有实现，比如List</li>
</ul>
<p><img src="https://i.imgur.com/QCdOcJR.png" alt=""></p>
<p>创建一个数组列表：</p>
<pre><code>ArrayList&lt;String&gt; musicLibrary = new ArrayList&lt;String&gt;();
</code></pre><p>对数组列表添加元素:</p>
<pre><code>musicLibrary.add(“Yellow Submarine”);
musicLibrary.add(&quot;Thriller&quot;);
//在特定位置添加元素
musicLibrary.add(0,&quot;Blue Suede Shoes&quot;);
</code></pre><p>访问数组列表中的元素:</p>
<pre><code>musicLibrary.get(0);
</code></pre><p>删除数组列表中的元素：</p>
<pre><code>musicLibrary.remove(2);
musicLibrary.remove(&quot;Thriller&quot;);
</code></pre><p>获取数组列表的长度：</p>
<pre><code>musiciLibrary.size();
</code></pre><p>下面列出了常见的<a href="https://docs.oracle.com/javase/tutorial/java/generics/types.html" target="_blank" rel="noopener">类型参数</a>： E - 元素（Java Collections Framework 大量用到） K - 键 N - 数字 T - 类型 V - 值 S、U、V 等 - 第 2 种、第 3 种、第 4 种类型。</p>
<p>创建数组列表的例子：</p>
<pre><code>ArrayList&lt;String&gt; words = new ArrayList&lt;String&gt;();
 words.add(&quot;one&quot;);
 words.add(&quot;two&quot;);
 words.add(&quot;three&quot;);
 words.add(&quot;four&quot;);
 words.add(&quot;five&quot;);
 words.add(&quot;six&quot;);
 words.add(&quot;seven&quot;);
 words.add(&quot;eight&quot;);
 words.add(&quot;seven&quot;);
 words.add(&quot;ten&quot;);
 Log.v(&quot;NumbersActivity&quot;,&quot;Words at index 0: &quot; + words.get(0));
</code></pre><h3 id="根据列表向布局添加剂TextView"><a href="#根据列表向布局添加剂TextView" class="headerlink" title="根据列表向布局添加剂TextView"></a>根据列表向布局添加剂TextView</h3><pre><code>LinearLayout rootView = (LinearLayout) findViewById(R.id.rootView);
TextView wordView = new TextView(this);
wordView.setText(words.get(0));
rootView.addView(wordView);
</code></pre><p>首先获取根视图，然后创建子视图，并设置子视图中的内容，最后，将子视图添加到父视图。</p>
<h3 id="循环"><a href="#循环" class="headerlink" title="循环"></a>循环</h3><h4 id="while循环"><a href="#while循环" class="headerlink" title="while循环"></a>while循环</h4><pre><code>while (条件){
    循环体
}
</code></pre><h4 id="for循环"><a href="#for循环" class="headerlink" title="for循环"></a>for循环</h4><pre><code>for(初始化count; 条件; 更新count){
    循环体
}
</code></pre><h3 id="视图回收"><a href="#视图回收" class="headerlink" title="视图回收"></a>视图回收</h3><p>内存资源是有限的，应该节约使用。如果我们要显示1000个联系人，创建1000个1000TextView，这样大大浪费了内存，因为显示在屏幕中的仅仅几个。如是考虑重复使用TextView。</p>
<p>视图回收：表示重复使用在屏幕上不再可见的视图。这里的视图是单行布局，包括LinearLayout、RelativeLayout。</p>
<p>采用ListView和ArrayAdapter根据需要在屏幕上显示的内容，创建阻隔的视图，即列表项行。</p>
<p><img src="https://i.imgur.com/QV3VRHa.png" alt=""></p>
<p>如果某个视图在屏幕上不再可见时，我们可以通过更改相关数据重复使用该视图，及更改视图中的数据，例如TextView中的文本或ImageView中的图片，我们不需要浪费事件从头创建整个视图。我们将这些多徐的视图放入Screap Pile中并等着回收利用。</p>
<p>当用户正在滚动查看屏幕，想查看列表的顶部，看看最新的推文，ListView意识到需要快速创建更多的列表项行，当用户滚动的时候，似乎列表项一直都存在，它可以从Scrap Pile中选择一个视图，（如果存在的话）重复使用，而不是从头创建。我们通过使用Scrap Pile中的视图创建了更多的视图行，然后就只需更改视图中的数据，以便为相关列表项显示正确的信息。ListView同时还很智能地知道位于屏幕底部的视图已经被滚出屏幕，这些对用户来说已经不可见，可以之间添加到Scrap Pile中。当用户往上滚动时，我们就可以使用这钱位于屏幕底部的列表项行。所有这些的目标是尽量创建很少的列表项，因为从XML向Java对象隐形膨胀视图的代价很大。</p>
<p><img src="https://i.imgur.com/kZ7FtQP.png" alt=""></p>
<p>当第一次将适配器与ListView相关联时，该ListView会询问“你想显示多少个项？”。ArrayAdapter知道这一信息，所以ListView对ArrayAdapter调用方法，它将在该方法中传入一个输入参数，即用户当前正在查看的列表位置。知道这一信息后，ArrayAdapter会查看数据的内部来源，如果列表是来源数据的话，它会查看列表，并获取相关信息。ArrayAdapter具有说明（Instructionss）来告诉ArrayAdapter如何创建列表项视图并返回ListView。当屏幕占满后，ListView将停止工作向ArrayAdapter寻求更多的列表项，列表项仅在需要是才创建。当视图被滚动离开屏幕后，它们就会被添加到这个Scrap Pile。然后，当我们请求新的列表项时，我们可以通过将这些视图在返回到ArrayAdapter重复使用它们。Listview将请求列表中特定位置的视图，同时传入之前用户的视图，例如，如果用户请求位置6的视图，会将可重复使用的以前的视图传给ArrayAdapter，ArrayAdapter可以通过在回收的视图中放入数据，使用回收的视图，比如，通过调用TextView setText()方法来更改这里的内容。</p>
<p><img src="https://i.imgur.com/YldFuZr.png" alt=""></p>
<pre><code>ArrayAdapter itemsAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, words);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(itemsAdapter);  
</code></pre><p>首先，使用new关键字以及具有三个输入参数的构造函数创建了一个ArrayAdapter对象，将其存储在itemsAdapter变量中，其数据类型是ArrayAdapter。第一个参数是Context，this指代NumbersActivity；第二个参数是列表项布局文件，这里指定为android.R.layout，因为Android框架实际上预定义了一个XMK布局文件，叫做simple_list_item_1，我们可以直接使用Android预定义的这个文件。最后一个参数是对象列表，即ArrayAdapter的数据来源。</p>
<p>前面使用ArrayList<string>创建字符串数组列表，讨论了泛型。因为ArrayList是个泛型类，我们可以重写成ArrayList<e>，E表示它是个泛型类<br>，E是类型参数或占位符，可以替换为具体的对象类型。例如，当我们创建ArrayList实例时，可以替换为字符串。创建一个泛型类，可以让我们稍后判断他将存储的数据类型，而不用创建多个具体的类，例如StringList类，IntegerList类等等。</e></string></p>
<p>第二行，找到布局中的ListView。</p>
<p>第三行，setAdapter方法输入参数是一个ListAdapter，ListAdatper是一个接口，由BaseAdapter抽象类实现某些方法，同时为其他方法保留为抽象方法，这时需要ArrayAdatper，ArrayAdapter是一个具体的类，所有方法都实现了。我们可以创建一个ArrayAdapter对象实例，并在我们的应用中使用。因此，ArrayAdapter是一个listAdapter，可以将itemsAdapter变量传入为listView.setAdapter()方法调用的输入参数。</p>
<p><img src="https://i.imgur.com/oESlPBy.png" alt=""></p>
<p>使用下拉菜单（Spinner）、网格视图（GridView）时，都需要使用到适配器ArrayAdapter。</p>
<p><img src="https://i.imgur.com/XSCkvuw.png" alt=""></p>
<h2 id="构造列表项布局"><a href="#构造列表项布局" class="headerlink" title="构造列表项布局"></a>构造列表项布局</h2><pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout
    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_height=&quot;match_parent&quot;
    android:layout_width=&quot;match_parent&quot;
    android:orientation=&quot;vertical&quot;
    android:padding=&quot;16dp&quot;&gt;

    &lt;TextView
        android:id=&quot;@+id/default_text_view&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        tools:text=&quot;one&quot;/&gt;

    &lt;TextView
        android:id=&quot;@+id/miwok_text_view&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        tools:text=&quot;一&quot;/&gt;

&lt;/LinearLayout&gt;
</code></pre><h3 id="tools命名空间"><a href="#tools命名空间" class="headerlink" title="tools命名空间"></a>tools命名空间</h3><p>在XML中，命名空间使元素之间没有名称冲突。<code>xmlns:android</code>是一个命名空间，我们已经在Android中使用的属性，例如android:layout_height等等以<code>android:</code>开头。</p>
<p>上面代码还添加一个命名空间，叫做tools命名空间</p>
<pre><code>xmlns:tools=&quot;http://schemas.android.com/tools&quot;
</code></pre><p>上面这行代码表示将tools前缀映射到这个命名空间<code>http://schemas.android.com/tools</code>。任何以tools开头的元素或属性都属于tools命名空间的一部分。</p>
<pre><code>tools:text=&quot;one&quot;
</code></pre><p>利用tools命名空间text来设置内容，在Android Studio的设计预览中将会显示此文本，但不会在运行时出现，这样为我们开发提供帮助。</p>
<h2 id="自定义类"><a href="#自定义类" class="headerlink" title="自定义类"></a>自定义类</h2><pre><code>package com.example.android.miwok;

/**
 * 创建了一个Wrod类，用户可以使用
 * 其包含一个默认翻译和一个Miwok翻译对于同一个单词
 * */
public class Word {
    private String mDefaultTranslation;
    private String mMiwokTranslation;

    public Word(String defaultTranslation, String miwokTranslaton)
    {
        mDefaultTranslation = defaultTranslation;
        mMiwokTranslation = miwokTranslaton;
    }

    /**
     * Get the Miwok Translation
     * @return
     */
    public String getMiwokTranslation() {
        return mMiwokTranslation;
    }

    /**
     * Get the defualt translation
     * @return string
     */
    public String getDefaultTranslation(){
        return mDefaultTranslation;
    }
}
</code></pre><p>根据自定义的类Word，可以创建Word对象数组列表，并传递给ArrayAdapter。</p>
<pre><code>ArrayList&lt;Word&gt; words = new ArrayList&lt;Word&gt;();
words.add(new Word(&quot;one&quot;,&quot;一&quot;));
words.add(new Word(&quot;two&quot;,&quot;二&quot;));
</code></pre><h2 id="自定义ArrayAdapter"><a href="#自定义ArrayAdapter" class="headerlink" title="自定义ArrayAdapter"></a>自定义ArrayAdapter</h2><pre><code>package com.example.android.miwok;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class WordAdapter extends ArrayAdapter&lt;Word&gt; {
    //构造函数
    public WordAdapter(Context context, ArrayList&lt;Word&gt; objects) {
        super(context, 0, objects);
    }
    /**@Override
    public View getView(int position,  View convertView,  ViewGroup parent)
    {
        return super.getView(position, convertView, parent);
    }*/
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Check if the existing view is being reused, otherwise inflate the view
        View listItemView = convertView;
        if(listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);
        }

        // Get the {@link AndroidFlavor} object located at this position in the list
        Word currentWord = getItem(position);

        // Find the TextView in the list_item.xml layout with the ID version_name
        TextView defaultTextView = (TextView) listItemView.findViewById(R.id.default_text_view);
        // Get the version name from the current AndroidFlavor object and
        // set this text on the name TextView
        defaultTextView.setText(currentWord.getDefaultTranslation());

        // Find the TextView in the list_item.xml layout with the ID version_number
        TextView miwokTextView = (TextView) listItemView.findViewById(R.id.miwok_text_view);
        // Get the version number from the current AndroidFlavor object and
        // set this text on the number TextView
        miwokTextView.setText(currentWord.getMiwokTranslation());

        // Return the whole list item layout (containing 2 TextViews)
        // so that it can be shown in the List
        return listItemView;
    }

}
</code></pre><p>在</p>
<pre><code>WordAdapter adapter = new WordAdapter(this,words);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
</code></pre>
      
    </div>
    
    
    

    
      <div>
        <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/images/wechat-qcode.jpg" alt="zxp wechat" style="width: 200px; max-width: 100%;"/>
    <div>欢迎关注微信公众号！</div>
</div>

      </div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div></div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/WeChatpay.jpg" alt="zxp 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/Alipay.jpg" alt="zxp 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zxp
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zxpgo.github.io/2018/11/09/Java数组、列表、循环和自定义类/" title="Java数组、列表、循环和自定义类">https://zxpgo.github.io/2018/11/09/Java数组、列表、循环和自定义类/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tag/APP开发/" rel="tag"># APP开发</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/11/08/模式识别(三)--判别函数及几何分类法/" rel="next" title="模式识别(三)--判别函数及几何分类法">
                <i class="fa fa-chevron-left"></i> 模式识别(三)--判别函数及几何分类法
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/11/18/台式安装Android Studio出现虚拟机无法启动/" rel="prev" title="台式安装Android Studio后出现虚拟机无法启动">
                台式安装Android Studio后出现虚拟机无法启动 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zODgxNC8xNTM0Mg=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.gif"
                alt="zxp" />
            
              <p class="site-author-name" itemprop="name">zxp</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">176</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">48</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/qq_25774883" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-globe"></i>CSDN</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/zxpgo/zxpgo" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-globe"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.linkedin.com/feed/" target="_blank" title="LinkedIn">
                      
                        <i class="fa fa-fw fa-globe"></i>LinkedIn</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="1165772354@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://theme-next.iissnan.com" title="Next主题" target="_blank">Next主题</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://blog.rexking6.top" title="青爷博客" target="_blank">青爷博客</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://me.csdn.net/download/qq_25774883" title="CSDN下载" target="_blank">CSDN下载</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.livere.com/" title="来必力" target="_blank">来必力</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://tongji.baidu.com/web/welcome/login" title="百度统计" target="_blank">百度统计</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://leancloud.cn/" title="LeanCloud" target="_blank">LeanCloud</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://ibruce.info/2015/04/04/busuanzi/" title="不蒜子" target="_blank">不蒜子</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://leetcode-cn.com/" title="LeetCode" target="_blank">LeetCode</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#数组Array"><span class="nav-number">1.</span> <span class="nav-text">数组Array</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数组列表ArrayList"><span class="nav-number">2.</span> <span class="nav-text">数组列表ArrayList</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#根据列表向布局添加剂TextView"><span class="nav-number">3.</span> <span class="nav-text">根据列表向布局添加剂TextView</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#循环"><span class="nav-number">4.</span> <span class="nav-text">循环</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#while循环"><span class="nav-number">4.1.</span> <span class="nav-text">while循环</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#for循环"><span class="nav-number">4.2.</span> <span class="nav-text">for循环</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#视图回收"><span class="nav-number">5.</span> <span class="nav-text">视图回收</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#构造列表项布局"><span class="nav-number"></span> <span class="nav-text">构造列表项布局</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#tools命名空间"><span class="nav-number">1.</span> <span class="nav-text">tools命名空间</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#自定义类"><span class="nav-number"></span> <span class="nav-text">自定义类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#自定义ArrayAdapter"><span class="nav-number"></span> <span class="nav-text">自定义ArrayAdapter</span></a></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div>
<script async src="https//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_pv" style='display:none'>
    本站总访问量 <span id="busuanzi_value_site_pv"></span> 
    <span class="post-meta-divider">|</span>
</span>
<span id="busuanzi_container_site_uv" style='display:none'>
    访问人数 <span id="busuanzi_value_site_uv"></span>
</span>
</div>


<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="copyright">&copy; 2018-8 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-"></i> Power by 
  </span>
  <span class="author" itemprop="copyrightHolder">zxp</span>
  
  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  




  
  <div id="lv-container" data-uid="MTAyMC8zODgxNC8xNTM0Mg==">
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
	</div>
  











  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("2AyV3DKioBSdoryrFLRohzjB-gzGzoHsz", "XynedcHyJCVCrTfbD4yYnodo");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "default";
      
          pbOptions.boxForm = "vertical";
      
          pbOptions.position = "top";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
      flOptions = {};
      
          flOptions.iconStyle = "box";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.4"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.4"></script>


  
  <script type="text/javascript" src="/js/src/exturl.js?v=5.1.4"></script>


  
  
  	 <!-- custom analytics part create by xiamo -->
<script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
<script>AV.initialize("2AyV3DKioBSdoryrFLRohzjB-gzGzoHsz", "XynedcHyJCVCrTfbD4yYnodo");</script>
<script>
function showTime(Counter) {
	var query = new AV.Query(Counter);
	$(".leancloud_visitors").each(function() {
		var url = $(this).attr("id").trim();
		query.equalTo("url", url);
		query.find({
			success: function(results) {
				if (results.length == 0) {
					var content = $(document.getElementById(url)).text() + ' 0';
					$(document.getElementById(url)).text(content);
					return;
				}
				for (var i = 0; i < results.length; i++) {
					var object = results[i];
					var content = $(document.getElementById(url)).text() + ' ' + object.get('time');
					$(document.getElementById(url)).text(content);
				}
			}
		});

	});
}

</script>
  
</body>
</html>
